from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.authentication import jwt_decode_handler

from activity.models import Gathering
from activity.serializers import GatheringSerializer
from users.models import User


class GatheringView(APIView):
    '''获取活动列表基本信息'''
    def get(self, request):
        gather = Gathering.objects.all()
        count = gather.count()
        serializer = GatheringSerializer(gather, many=True)
        response_data = {
            "count": count,
            "next": "",
            "previous": "",
            "results": serializer.data,
        }
        return Response(response_data)


class GatherView(APIView):
    '''活动的具体信息的获取'''
    def get(self, request, pk):
        gather = Gathering.objects.get(id=pk)
        serializer = GatheringSerializer(gather)
        return Response(serializer.data)


class GatherApplicationView(APIView):
    '''报名接口'''
    def post(self, request, pk):
        data = request.data
        token = data.get('token')[4:]
        toke_user = jwt_decode_handler(token)
        user_id = toke_user['user_id']
        user = User.objects.get(id=user_id)
        gather = Gathering.objects.get(id=pk)
        gather.users.add(user)
        response_data = {
            "success": True,
            "message": "OK"
        }
        return Response(response_data)
# Create your views here.
